package com.supersoul.myself.service.impl;

import com.supersoul.myself.dao.CategoryDao;
import com.supersoul.myself.entity.Category;
import com.supersoul.myself.entity.User;
import com.supersoul.myself.ex.ServiceException;
import com.supersoul.myself.service.CategoryService;
import com.supersoul.myself.util.PageVO;
import com.supersoul.myself.util.UpdateTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryDao categoryDao;

    @Override
    public String saveCategory(Category category, User user) throws ServiceException {
        String id = category.getId();
        if (null == id) {
            category.buildCreate();
            category.setCreatorId(user.getId());
            category.setCreatorName(user.getUserName());
        } else {
            category.setUpdateTime(new Date());
            category.setUpdatorId(user.getId());
            category.setUpdatorName(user.getUserName());
            Category categorySource = getCategory(id);
            UpdateTool.copyNullProperties(categorySource, category);
        }
        categoryDao.save(category);
        return category.getId();
    }

    @Override
    public void delCategoryById(String id) throws ServiceException {
        Category category = new Category();
        category.setId(id);
        categoryDao.delete(category);
    }


    @Override
    public Category getCategory(String id) throws ServiceException {
        return categoryDao.findById(id).orElse(null);
    }

    @Override
    public Page<Category> getCategoryByUser(PageVO pageVO, User user) throws ServiceException {
        List<Sort.Order> orderList = new ArrayList<>();
        orderList.add(new Sort.Order(Sort.Direction.DESC, "createTime"));
        Pageable pageable = PageRequest.of(pageVO.getPageNum(), pageVO.getPageSize(), Sort.by(orderList));
        return categoryDao.findByCreatorId(user.getId(), pageable);
    }

}
